from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from .models import User
from .forms import CustomUserCreationForm, CustomUserChangeForm

class CustomUserAdmin(UserAdmin):
    # 表单配置
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = User
    
    # 列表页显示字段（优化后）
    list_display = [
        'username',
        'nickname',
        'user_type',
        'phone',
        'email',
        'is_active',
        'is_verified',
        'last_active',
        'points'
    ]
    
    # 列表页过滤器（优化后）
    list_filter = [
        'user_type',
        'is_active',
        'is_verified',
        'is_staff',
        'city',
        'date_joined'
    ]
    
    # 字段分组配置（优化后）
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('微信信息'), {
            'fields': (
                'openid',
                'unionid',
                'nickname',
                'wx_avatar',
            ),
            'classes': ('collapse',)  # 默认折叠
        }),
        (_('个人信息'), {
            'fields': (
                'email',
                'phone',
                'avatar',
                'bio',
                'points',
                ('city', 'district'),
            )
        }),
        (_('权限与状态'), {
            'fields': (
                'user_type',
                'is_active',
                'is_verified',
                'is_staff',
                'is_superuser',
                'groups',
                'user_permissions'
            )
        }),
        (_('重要日期'), {
            'fields': (
                'last_login',
                'date_joined',
                'last_active'
            ),
            'classes': ('collapse',)
        }),
    )
    
    # 添加用户表单字段（优化后）
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': (
                'username',
                'password1',
                'password2',
                'user_type',
                'is_active',
                'is_staff'
            )
        }),
    )
    
    # 搜索和排序配置
    search_fields = ('username', 'nickname', 'phone', 'email', 'openid')
    ordering = ('-date_joined',)
    filter_horizontal = ('groups', 'user_permissions',)
    readonly_fields = ('last_active', 'date_joined', 'last_login')
    
    # 自定义动作
    actions = ['make_active', 'make_inactive', 'verify_users']
    
    @admin.action(description=_('激活选中用户'))
    def make_active(self, request, queryset):
        queryset.update(is_active=True)
    
    @admin.action(description=_('冻结选中用户'))
    def make_inactive(self, request, queryset):
        queryset.update(is_active=False)
    
    @admin.action(description=_('验证选中用户'))
    def verify_users(self, request, queryset):
        queryset.update(is_verified=True)

# 注册模型
admin.site.register(User, CustomUserAdmin)